More results...

Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
post
page
Python IDE Dashboard

The Marine Biologist’s Python Challenge

For this challenge we will write a program that would be useful for a team of marine biologists working on a conservation project along the coast. Their aim is to estimate the population of sea turtles living in a particular bay. Since it’s impossible to count every single turtle in the water, the biologists use a clever technique known as the capture-recapture method.

Your challenge is to create a Python program that helps our team of marine biologists estimate the total sea turtles population based on data collected during two observation trips.

What Is the Capture-Recapture Method?

The capture-recapture method is commonly used by wildlife researchers to estimate animal populations without counting every individual.

Here’s how it works:

  1. First Capture: A group of animals is captured, marked (e.g. tagged), and released.
  2. Second Capture: Later, another group is captured, and researchers count how many are already marked.
  3. Using the overlap between the two groups (the number of animals marked within the second capture), we can estimate the total population with the following formula:

So let’s use the following example to better understand how this formula works:
During their first trip, the marine biologists catch and tag 80 sea turtles before releasing them.
On a second trip a few weeks later, they catch 110 sea turtles, 25 of which are already tagged.

Using this information, we can apply the capture-recapture formula to estimate the total population of sea-turtles living in the bay:

Python Challenge

Your task is to write a Python program that:

    Asks the user to input:

      The number of turtles tagged in the first capture.
      The number of turtles caught in the second capture.
      The number of recaptured tagged turtles in the second sample.

    Applies the capture-recapture formula.
    Outputs the estimated total population of sea turtles.

Python Code

Ready to dive in? Start coding and help the marine biologists make a difference!

Testing

Once your code is done, complete the following tests to check that your code is working as it should:

Test # Input Values Expected Output Actual Output
#1 First Capture: 80
Second Capture: 110
Recaptures: 25
Estimated Population Size: 352
#2 First Capture: 90
Second Capture: 70
Recaptures: 12
Estimated Population Size: 525
#3 First Capture: 70
Second Capture: 50
Recaptures: 0
We cannot estimate the population size with this data (0 recaptures)

Why It Matters

The capture-recapture approach is widely used by marine biologists, ecologists, and conservationists to study animal populations in a humane and efficient way. By writing a Python program for this method, you’re not only learning about real-world data science, but also supporting work that protects endangered species!

Extra Challenge

The team of marine biologists would like to improve the accuracy of their sea turtles population size estimate. To do so, they have decided to conduct this capture/recapture experiment six times, once every week over a period of 6 weeks. They have recorded their data in a file called Sea-Turtles.csv as follows:

first capture,second capture,number of retakes
80,110,25
76,70,16
90,70,19
98,64,18
82,72,18
85,78,20

We have saved this csv file as a separate tab in the Python IDE below.

The following Python code can be used to read our CSV file line by lineand extract the data from each line:

file = open("Sea-Turtles.csv","r")

for line in file:
   data = line.split(",")
   firstCapture = int(data[0])  
   secondCapture = int(data[1])
   retakes = int(data[2])
   print("First Capture: " + str(firstCapture) + " - Second Capture: " + str(secondCapture) + " - Retakes: " + str(Retakes))
  
file.close()

Your task is to tweak the following code to calculate the estimated population size for each experiment and work out the average population size over these 6 experiments.

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area

Stock Level Checker Program – Python Challenge

With this Python challenge, we’re going to focus on using file handling techniques to create a simple yet practical program to be used by a shop assistant to quickly check their stock levels. The goal is to write a Python script that allows users to check the availability of clothing items in stock. The program will prompt the user to select a piece of clothing, a size, and a colour, and then it will check a CSV file to see if the item is available.

CSV File?

To begin, we will need a CSV file that contains the stock information. CSV files (Comma Separated Values) are text files that store data where each record is stored on a line and each field is separated using a comma “,”. Sometimes we use other symbols instead of the comma such as a semi-colon “;” or a pipe “|”. Below is an example of what the CSV file might look like:

item,size,color,quantity
t-shirt,S,red,5
t-shirt,M,blue,3
t-shirt,L,red,2
t-shirt,M,red,0
t-shirt,S,blue,0
t-shirt,S,green,1
shorts,M,blue,1
shorts,L,green,0
shorts,S,green,2
shorts,S,blue,3
cap,L,red,4
cap,M,white,2
cap,M,black,0
cap,S,red,5

We have saved this data into a CSV file called stock.csv available as a separate tab in the Python IDE below.

The following Python code can be used to read our CSV file line by line and extract the data from each line:

file = open("stock.csv","r")

for line in file:
   data = line.split(",")
   item = data[0]  
   size = data[1]
   colour = data[2]
   stockLevel = int(data[3])
   print(item + " - " + size + " - " + colour + " - Quantity in Stock: " + str(stockLevel))
  
file.close()

Python Code

Your task is to complete the code provided below to perform the following tasks:
Your task is to create a Python program that performs the following steps:

    Prompt the user to enter a piece of clothing (e.g. t-shirt, shorts, cap).
    Ask the user to select a size (e.g. S, M, L).
    Request the user to choose a colour (e.g. red, blue, green, white, black).
    Check a CSV file to see if the item is in stock.
    Display a message indicating whether the item is available or out of stock.

Note that an item is out of stock if its stock level is zero or if it is not listed in the CSV file.

Testing

Once your code is done, complete the following tests to check that your code is working as it should:

Test # Input Values Expected Output Actual Output
#1 Item: T-Shirt
Size: L
Colour: Red
This item is in stock (Stock Level: 2)
#2 Item: Cap
Size: M
Colour: Black
This item is out of stock
#3 Item: Shorts
Size: S
Colour: Blue
This item is in stock (Stock Level: 3)
#4 Item: Cap
Size: L
Colour: White
This item is out of stock

Next step…

This challenge is a great way to practise file handling in Python. By completing this task, you’ll gain experience in reading from CSV files and processing user input. Feel free to expand the program by adding more features, such as updating the stock quantity or allowing users to add new items to the stock. You may also make your program more robust by validating user inputs and converting the case to match the case used in the CSV file. (e.g. size automatically converted to uppercase and colour automatically converted to lowercase).

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area
Tagged with:

Ada Lovelace and the First Computer Algorithm

In this post we will focus on a very specific algorithm called the Note G algorithm, written in 1843 by Ada Lovelace. Born in 1815, Ada Lovelace is celebrated as a visionary whose work laid the groundwork for modern computing. Among her most notable contributions is the Note-G algorithm, widely regarded as the first computer algorithm, even though the machine it was designed for—the Analytical Engine—was never built.

The Analytical Engine: A Vision Ahead of Its Time

The Analytical Engine was a mechanical general-purpose computer proposed by Charles Babbage. Although it remained a theoretical construct, the engine’s design was revolutionary. It was intended to perform complex calculations and could be programmed using punched cards, a concept that would later influence the development of early computers.

The Note-G Algorithm: The First of Its Kind

Ada Lovelace’s Note-G algorithm was designed to be implemented on the Analytical Engine. The algorithm was part of her translation and expansion of an Italian article on the engine, where she detailed how the machine could compute Bernoulli numbers. This work is significant because it represents the first explicit description of a step-by-step process for a machine to perform a complex calculation—the essence of what we now call an algorithm.

Diagram of an algorithm for the Analytical Engine for the computation of Bernoulli numbers, from Sketch of The Analytical Engine Invented by Charles Babbage by Luigi Menabrea with notes by Ada Lovelace

Bernoulli Numbers?

For those unfamiliar with the term, Bernoulli numbers are a sequence of rational numbers with deep connections to number theory. They appear in various areas of mathematics, including the expansion of trigonometric functions and the calculation of sums of powers of integers. The sequence starts with B₀ = 1, B₁ = -1/2, B₂ = 1/6, and so on, with each number defined by a specific recursive formula.

Lovelace’s algorithm to compute these numbers was ground breaking because it demonstrated that a machine could perform tasks that went beyond simple arithmetic, showcasing the potential for automated computation.

Testing the Note-G Algorithm

Let’s use our Analytical Engine emulator to test Ada Lovelace’s algorithm. The algorithm provided below is a direct translation of Ada Lovelace’s algorithm (See picture above). It is used to calculate Bernoulli Number 7( B7).

To work out the value of B7, the algorithms relies on the values of B1, B3 and B5.

Bj Fraction Decimal
B1 1/6 +0.166666666
B3 −1/30 −0.033333333
B5 1/42 +0.023809523

As the Store of the analytical engine can only store integer values (whole numbers with no decimal), we are shifting the values being calculated by 12 digits.

For instance the output of our program should be read as follows: B7 = -33333333336 x 10-12 = 0.033333333336 ≈ -1/30
Charles Babbage’s Analytical Engine SimulatorOpen in new tab/window

Code Explanation

To transpose Ada Lovelace’s Note G algorithm into a set of cards/instructions to be processed by the analytical engine the program will first need to loads some values in the store using Number cards (N). (You can check at the end of this post for a full list of instructions that can be processed by the Analytical Engine emulator.)

N1 1
N2 2
N3 4
.Bernoulli numbers shifted by 12 digits
N21 166666666667
N22 -33333333333
N23 23809523809
N24 0

Then the Note G algorithms contains 25 arithmetic operations clearly described on Ada Lovelace’s note provided below. Let’s look at the first operation:

For instance the first operation is a multiplication of variable V2 and V3. V stands for variable, each variable being stored using one column of the store. e.g. V2 refers to the 2nd column of the store. As indicated the result of this operation will be stored three times in column V4, V5 and V6.
This is how this operation would be coded using punched cards:

X     .Load operation card for multiplication
L2    .Load V2 (=2)
L3    .Load V3 (=4)
S4    .Store the result of V2xV3 = 2x4 = 8  in column 4 (V4)
S5    .Store the result in column 5 (V5)
S6    .Store the result in column 6 (V6)

We can now move to the next operation in the algorithm which is a subtraction:

With this operation we are subtracting V1 from V4 and storing the result in V4. (V4 = V4 – V1).This is how this operation would be coded using punched cards:

-     .Load operation card for subtraction
Z4    .Load V4 (=8) (and reset the column to 0)
L1    .Load V3 (=1)
S4    .Store the result of V4-V1 = 8-1 = 7  in column 4 (V4)

We can use this approach to transpose all 25 operations using the relevant punched cards. You can see the result in the emulator and use it to test the Note-G algorithm.

Full Code for Ada Lovelace’s Note G Algorithm:

.Note-G Algorithm
.An algorithm to calculate Bernoulli Number B7 (-1/30)
.Based on Ada Lovelace's Note - G algorithm
N1 1
N2 2
N3 4
.Bernoulli numbers shifted by 12 digits
N21 166666666667 .B1
N22 -33333333333 .B3
N23 23809523809 .B5
N24 0 .B7
.1
X
L2
L3
S4
S5 
S6
.2
-
Z4
L1
S4
.3
+
Z5
L1
S5
.4
/
Z4
<12
Z5
S11'
.5
Z11
L2
S11'
.6
-
Z13
Z11
S13
.7
L3
L1
S10
.8
+
L2
Z7
S7
.9
/
L6
<12
L7
S11'
.10
X
L21
L11
S12
L12
>12
L1
S12
.11
+
Z12
Z13
S13
.12
-
Z10
L1
S10
.13
-
Z6
L1
S6
.14
+
L1
Z7
S7
.15
/
L6
<12
L7
S8'
.16
X
Z8
Z11
S11
L11
>12
L1
S11
.17
-
Z6
L1
S6
.18
+
L1
Z7
S7
.19
/
L6
<12
L7
S9'
.20
X
Z9
Z11
S11
L11
>12
L1
S11
.21
X
L22
L11
S12
L12
>12
L1
S12
.22
+
Z12
Z13
S13
.23
-
Z10
L1
S10
.13 -REPEAT-
-
Z6
L1
S6
.14
+
L1
Z7
S7
.15
/
L6
<12
L7
S8'
.16
X
Z8
Z11
S11
L11
>12
L1
S11
.17
-
Z6
L1
S6
.18
+
L1
Z7
S7
.19
/
L6
<12
L7
S9'
.20
X
Z9
Z11
S11
L11
>12
L1
S11
.21
X
L23
L11
S12
L12
>12
L1
S12
.22
+
Z12
Z13
S13
.23
-
Z10
L1
S10
.24
-
Z24
L13
S24
P
.25
L1
Z3
S3
Z6
Z7
B
H
Charles Babbage’s Analytical Engine SimulatorOpen in new tab/window

Analytical Engine Instruction Set

The table below describes the different instructions/punched cards the analytical engine would have been able to process:

Opcode Instruction Example Description
N Number N1 5 Used to store a given number (e.g. 5) in the store at a specific location (e.g. 1)
L Load L2 Load a value from the store, at a specified location (e.g. 2) to the Mill Ingress axis, leaving the store column unchanged.
Z Load Z2 Load a value from the store, at a specified location/column (e.g. 2) to the Mill Ingress axis, resetting the store column to 0.
S Save S2 Store the value currently in the Mill Egress axis to a given location/column in the Store.
+ Add + Add the values in the two Ingress Axes (ignoring the contents of the Primed Ingress Axis), and the result of this addition is stored in the Egress Axis.
Subtract Subtract the values in the two Ingress Axes (ignoring the contents of the Primed Ingress Axis), and the result of this subtraction is stored in the Egress Axis.
x Multiply Multiply the values in the two Ingress Axes (ignoring the contents of the Primed Ingress Axis), and the result of this multiplication is stored in the Egress Axis.
/ Divide / The value in the first Ingress Axis is divided by the value in the second Ingress Axis. The quotient is placed on the Primed Egress Axis and the remainder on the Egress Axis.
< Step up <6 Step up (left right) by n digits in the Ingress Axis. e.g. <3 to multiply the Ingress value by 1,000.
> Step down >6 Step down (shift right) by n digits in the Ingress Axis. e.g. >3 to divide the Ingress value by 1,000.
CB+ Back Always CB+7 To skip backward (and repeat) a given number of cards in the reader.
CB? Back only if run-up lever is set CB?7 To skip backward (and repeat) a given number of cards in the reader if run-up lever is set.
CF+ Forward Always CF+7 To skip forward a given number of cards in the reader.
CF? Forward only if run-up lever is set CF?7 To skip forward a given number of cards in the reader if run-up lever is set.
P Print P Print the value on the mill axis that the most recent operation most recently modified (e.g. the Mill Egress axis after an arithmetic operation, the Ingress axis after a L instruction, etc.).
B Bell B Ring the bell to get the attention of the engine attendant.
H Halt H Stop the engine. Stop the execution of the program.

Read More…

Check the following two blog posts:

Charles Babbage’s Analytical Engine Emulator

In 19th-century London, Charles Babbage, an English mathematician and inventor, embarked on a groundbreaking quest to build the Analytical Engine, a mechanical precursor to the modern computer. Frustrated by errors in manual calculations, Babbage envisioned a machine capable of performing complex computations through programmable instructions. His collaboration with Ada Lovelace, who wrote the first computer program for the engine, revealed its full potential, laying the foundation for the digital age and establishing Lovelace as the world’s first computer programmer.

The Genesis of the Analytical Engine

Charles Babbage’s journey began with the Difference Engine, a mechanical calculator designed to compute polynomial functions. You can use our online difference engine emulator to find out more about this invention. Babbage’s ambition extended far beyond simple calculations: he envisioned a machine capable of performing any mathematical operations, guided by a set of instructions — a concept we now recognise as programming. This vision culminated in the design of the Analytical Engine.

The Collaboration with Ada Lovelace

Ada Lovelace, the daughter of the poet Lord Byron, is celebrated for her collaboration with Babbage on the Analytical Engine. Lovelace’s deep understanding of the engine’s potential led her to write a series of notes translating and expanding upon an Italian article about the engine. In these notes, she described an algorithm for the engine to compute Bernoulli numbers, which is widely regarded as the first computer program. Her visionary insights into the engine’s capabilities earned her the title of the world’s first computer programmer.

Main Components of the Analytical Engine

The Analytical Engine comprised several key components, each serving a distinct function:

The Mill: This was the computational heart of the engine, responsible for performing arithmetic operations. It was akin to the central processing unit (CPU) in modern computers, executing instructions and manipulating data.

The Store: This component served as the memory of the engine, holding numbers and intermediate results. It was analogous to today’s random-access memory (RAM), storing data that the Mill could retrieve and process. The approach used to store decimal numbers (as opposed to binary numbers in modern computers) using mechanical cog wheels was already a key concept of Charles Babbage’s difference engine.

The Card Reader: The engine was designed to accept input through punched cards, a concept borrowed from the Jacquard loom, a device used in the textile industry: The loom used punched cards to control the weaving of intricate patterns.

The Control Unit: This component directed the sequence of operations, determining which instructions the Mill should execute and when. It was the precursor to the control unit in modern computers, managing the flow of data and instructions.

The PrinterThe result of calculations performed by the Mill was envisioned to be either printed or punched onto cards.

The Analytical Engine Emulator

Despite its revolutionary design, the Analytical Engine was never fully constructed. This is mainy due to the technological limitations and high costs of precision engineering in the 19th century, as well as Babbage’s struggles to secure consistent funding and support for the project.

From the documentation produce by Charles Babbage and Ada Lovelace we can however understand and predict how the machine was intended to operate. The documentation describes the different sets of punched cards (instructions) that the machine had been designed to process. The work of John Walker published on his website (fourmilab), will provide you detailed information about the Analytical Engine and how it operates.

We have recreated here a functioning emulator the Analytical Engine of the to demonstrate how the machine was designed to operate. This emulator include pre-built programs that you can load and test online.
Charles Babbage’s Analytical Engine SimulatorOpen in new tab/window

The Inspiration Behind Punched Cards

Babbage’s idea of using punched cards to program the Analytical Engine was inspired by the Jacquard loom, invented by Joseph Marie Jacquard in 1804. The loom used punched cards to automate the weaving of complex patterns, revolutionising the textile industry. Babbage recognised the potential of this technology for programming his engine, allowing it to perform complex sequences of operations automatically.

The table below describes the different instructions/punched cards the analytical engine would have been able to process:

Opcode Instruction Example Description
N Number N1 5 Used to store a given number (e.g. 5) in the store at a specific location (e.g. 1)
L Load L2 Load a value from the store, at a specified location (e.g. 2) to the Mill Ingress axis, leaving the store column unchanged.
Z Load Z2 Load a value from the store, at a specified location/column (e.g. 2) to the Mill Ingress axis, resetting the store column to 0.
S Save S2 Store the value currently in the Mill Egress axis to a given location/column in the Store.
+ Add + Add the values in the two Ingress Axes (ignoring the contents of the Primed Ingress Axis), and the result of this addition is stored in the Egress Axis.
Subtract Subtract the values in the two Ingress Axes (ignoring the contents of the Primed Ingress Axis), and the result of this subtraction is stored in the Egress Axis.
x Multiply Multiply the values in the two Ingress Axes (ignoring the contents of the Primed Ingress Axis), and the result of this multiplication is stored in the Egress Axis.
/ Divide / The value in the first Ingress Axis is divided by the value in the second Ingress Axis. The quotient is placed on the Primed Egress Axis and the remainder on the Egress Axis.
< Step up <6 Step up (left right) by n digits in the Ingress Axis. e.g. <3 to multiply the Ingress value by 1,000.
> Step down >6 Step down (shift right) by n digits in the Ingress Axis. e.g. >3 to divide the Ingress value by 1,000.
CB+ Back Always CB+7 To skip backward (and repeat) a given number of cards in the reader.
CB? Back only if run-up lever is set CB?7 To skip backward (and repeat) a given number of cards in the reader if run-up lever is set.
CF+ Forward Always CF+7 To skip forward a given number of cards in the reader.
CF? Forward only if run-up lever is set CF?7 To skip forward a given number of cards in the reader if run-up lever is set.
P Print P Print the value on the mill axis that the most recent operation most recently modified (e.g. the Mill Egress axis after an arithmetic operation, the Ingress axis after a L instruction, etc.).
B Bell B Ring the bell to get the attention of the engine attendant.
H Halt H Stop the engine. Stop the execution of the program.

Similarities and Differences with Modern Computers

The Analytical Engine shared several similarities with modern computers:

Programmability: Both can be programmed to perform a wide range of tasks, guided by a set of instructions.
Memory and Processing: The Store and Mill in the Analytical Engine are analogous to memory and CPU in modern computers.
Input/Output: Both use mechanisms for inputting data and outputting results, although the methods differ.

However, there are also significant differences:

Mechanical vs. Electronic: The Analytical Engine was purely mechanical, relying on gears and levers, while modern computers are electronic, using transistors and circuits.
Size and Speed: Modern computers are exponentially faster and more compact than the Analytical Engine, which was never fully constructed due to its complexity and the limitations of 19th-century technology.
Decimal vs. Binary: The Analytical Engine processed decimal numbers, reflecting the mathematical conventions of its time. In contrast, modern computers operate using binary numbers, which are more efficient for electronic computation.

Read More…

Check the following two blog posts:

Creating a Visual Hierarchy in HTML/CSS

In this post, we will explore the concept of visual hierarchy and how you can use your coding skills to recreate a specific visual layout. By the end of this challenge, you will have a better understanding of how to draw the reader’s attention to specific sections of a webpage using HTML and CSS. But first, let’s start with a short experiment. Check the picture below and check if it worked.

Did it work? In other words, did you read the text in the order mentioned on the picture?

Understanding the Concept of Visual Hierarchy

Visual hierarchy is a design principle that guides the viewer’s eye through different elements on a graphic or on a page, emphasising some over others. It is crucial in both print and digital media to ensure that the most important information stands out. For example, on a book cover, the title or the author’s name might be emphasised using larger fonts, bold colours, or strategic placement.

In web design, visual hierarchy helps users navigate and understand the content quickly. By using different sizes, colours, and placements, you can guide the user’s attention to the most critical parts of your webpage.

Coding Challenge: Recreate the Visual Hierarchy

Your task is to recreate the visual hierarchy similar to the one shown in the above image, using HTML and CSS. This layout uses text elements of varying sizes and positions to create a clear hierarchy.

To achieve this layout, you will need to use several CSS properties that control text formatting, positioning, and spacing. Here are some of the main properties you’ll use:

CSS Properties to Format Text:

  • font-family: Changes the font type used for the text. (e.g. Arial, Times New Roman, Verdana, etc.)
  • font-size: Controls the size of the text. Larger sizes draw more attention.
  • font-weight: Makes text bold or normal. Bold text stands out more.
  • font-style: Makes text italic or normal.
  • color: Sets the colour of the text. Contrasting colours can highlight important information.
  • text-align: Aligns text to the left, right, center, or justified.

Positioning and Alignment:

  • position: Allows you to position elements using values like static, relative, absolute, fixed, or sticky.
  • top, bottom, left, right: Used with position to specify the exact placement.
  • display: Controls the display behavior (e.g., block, inline, flex).

Spacing:
To understand the concepts of margin, padding and borders you may want to do some quick research on understanding the “CSS Box Model”.

  • margin: Adds space outside an element, pushing other elements away.
  • padding: Adds space inside an element, increasing the area between the content and the border.
  • border: Adds a border around an element, which can be used to separate or highlight sections.

HTML/CSS Code

Here is a basic example to get you started. You will need to apply more CSS properties to the different elements of the page to create your own visual hierarchy.

See the Pen
Creating a Visual Hierarchy
by 101 Computing (@101Computing)
on CodePen.


unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area

Charles Babbage’s Difference Engine Emulator

In this blog post we will investigate the work of Charles Babbage with a particular focus on one of his most famous inventions: the Difference Engine. This invention constitutes a pioneering step in Computer Science. We will also explore the collaboration between Charles Babbage and Ada Lovelace who is considered to be the first computer programmer!

Who Was Charles Babbage?

Charles Babbage (1791-1871) was an English mathematician, philosopher, inventor, and mechanical engineer. He is widely recognised as one of the pioneers of computing, having designed the first automatic computing engines. Babbage’s contributions extended beyond computing; he also invented the cowcatcher for trains, improved the British postal system, and made significant advancements in cryptography and operations research. His work laid the foundation for modern computing and had a profound impact on the development of computer science.

What is the Difference Engine?

The Difference Engine is an automatic mechanical calculator designed to tabulate polynomial functions. It was conceived by Charles Babbage in the 1820s and was intended to produce error-free mathematical tables, particularly logarithm tables used in navigation. The engine operated on the method of finite differences, which allowed it to compute values of polynomial functions using a small set of coefficients.

The Difference Engine was a significant advancement over previous calculating machines. It used the decimal number system and was powered by a hand crank. The machine was designed to calculate a series of values and print the results automatically in a table. This automation was crucial because it reduced the likelihood of human error in the calculation and transcription of mathematical tables, which were essential for various scientific and engineering applications.

The primary use of the Difference Engine was to produce accurate mathematical tables. These tables were vital for navigation, engineering, and scientific research. Before the Difference Engine, tables were calculated by hand, a process that was time-consuming and prone to errors. Babbage’s machine aimed to make this process more efficient and reliable. The British government supported the project, hoping it would make the production of tables more economical and accurate.

Difference Engine Simulator

Use our online Difference Engine Emulator to find out more about Charles Babbage’s invention. In the example below, the engine is set up to tabulate the polynomial values of Euler’s polynomial: P(x)=x2+x+41

The particularity of this polynomial is that it generates only prime values for the first 40 integer values of x, starting with x=0: F(0) = 41, F(1) = 43, F(2) = 47, ⋯, F(39) = 1601. You can use the emulator to tabulate the first 40 values of Euler’s polynomial one value at a time using the following button:

Alternatively, you can use the “Settings” button to enter your own polynomial function.


The Difference Engine is considered one of the earliest examples of a computing device and a precursor to modern computers. Although Babbage’s original design was never fully realised during his lifetime due to technological and financial constraints, his concepts influenced the development of later computing machines. The principles behind the Difference Engine, such as the use of mechanical components to perform calculations and the automation of repetitive tasks, are fundamental to modern computing.

Babbage’s work also inspired future generations of inventors and scientists. His ideas about programmable machines and the use of punched cards for input, which he developed further in his Analytical Engine, were influential in the design of early electronic computers. The Difference Engine represents a crucial step in the evolution of computing, bridging the gap between manual calculation and automated computation.

Ada Lovelace’s Contribution to Charles Babbage’s Work

Ada Lovelace, born Augusta Ada Byron in 1815, was an English mathematician and writer. She is widely recognised for her work on Charles Babbage’s early mechanical general-purpose computer, the Analytical Engine. Her contributions to the field of computer science were ground-breaking and have earned her the title of the first computer programmer.

Ada Lovelace met Charles Babbage in 1833 when she was just 17 years old. Babbage, impressed by her intellectual capabilities, became her mentor and friend. Lovelace was fascinated by Babbage’s Difference Engine and later became deeply involved in his work on the Analytical Engine. Their collaboration was marked by a shared enthusiasm for scientific and mathematical inquiry, and their partnership played a crucial role in the early development of computing.

In 1842, Lovelace translated an article by Italian engineer Luigi Menabrea about the Analytical Engine from French to English. During this translation, she added extensive notes that were longer than the original article itself. These notes, published in 1843, included what is considered the first algorithm intended to be carried out by a machine, making Lovelace the first computer programmer. Her notes also explored the potential of the Analytical Engine beyond mere calculations, suggesting that it could be used for more complex tasks, including composing music and manipulating symbols.

Lovelace’s contributions laid the theoretical groundwork for computer programming. She understood that the Analytical Engine could follow a sequence of instructions — a program — to perform complex calculations. Her vision went beyond the capabilities of the machine as envisioned by Babbage, recognising that the engine could work with “other things besides number,” such as symbols and letters. This foresight was a fundamental shift from calculation to computation, a concept that is central to modern computing.

Ada Lovelace’s work has had a lasting impact on the field of computer science. Her insights into the potential of computing machines were far ahead of her time. Although the Analytical Engine was never fully built during her lifetime, her ideas influenced the development of early computers. In recognition of her contributions, a programming language developed by the U.S. Department of Defence in the 1970s was named “Ada” in her honour. Additionally, Ada Lovelace Day, celebrated on the second Tuesday of October, honours women’s contributions to science, technology, engineering, and mathematics (STEM).

Find Out More about the Difference Engine

About Charles Babbage Difference Engine №2 – Source: Science Museum Group
User Manual for the Difference Engine №2 – Source: Science Museum Group

Read More about the collaboration between Charles Babbage and Ada Lovelace

Internet History Timeline – Python Challenge

In this challenge, you will create two Python programs that quizzes users on key milestones from the history of the internet. Our program will let the player opt between two different types of quizzes:

  • Guess The Year Quiz: The program will randomly pick a key milestones from a provided Internet History Timeline (stored as a CSV file) and ask users to guess the year in which the selected milestone occurred.
  • Before or After Quiz: This second quiz will will randomly pick two key milestones from the Internet History Timeline and ask the user to guess which of these two key milestones occurred first .

By completing this challenge, you will improve your Python skills while learning about the fascinating history of the internet.

Internet History Timeline

There are many factors which have had a major impact in the development of the Internet since the late 1960s to the present day. Technological inventions in computer hardware, network concepts and protocols but also the launch of widely used websites which have been adopted by millions if not billions of Internet users worldwide.

Let’s revisit some of these key milestones presented on the following timeline:

Internet History TimelineOpen a new window

Guess The Year Quiz

We have started the code to create a “Guess The Year Quiz”. Our code randomly picks up a milestone from the internet-timeline.csv file provided in the tab below. It then display this milestone on the screen and ask the user to guess the year of this milestone.

Our code is however incomplete. To finalise this quiz you will need to:

    Check the annotated code provided below to see how the code randomly pick a question using the provided CSV file
    Use a loop to generate 10 different questions
    Add a scoring system to calculate and display a total score out of 10.

Before or After Quiz

Now that you understand how the code for the “Guess The Year” quiz works, re-use a similar approach to create the second quiz called “Before or After?”. Your program will need to:

    Randomly pick two milestones from the Internet History Timeline (using the provided CSV file)
    Display both milestones on the screen
    Ask the user to guess which of the two milestones occurred first
    Check the user’s guess and provide feedback on their guess
    Use a loop to generate 10 different questions
    Add a scoring system to calculate and display a total score out of 10.
unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area
Tagged with:

Lossless Compression Algorithms using Python

In today’s data-driven world, efficient storage and transmission of information are more critical than ever. Lossless compression techniques play a pivotal role in achieving this efficiency by reducing data size without compromising its integrity. Unlike lossy compression, which sacrifices some data to achieve higher compression rates, lossless methods ensure that the original data can be perfectly reconstructed from its compressed form. This makes lossless compression ideal for applications where data accuracy is paramount, such as text files, computer programs, executables, and databases.

In this blog post, we will focus on two fundamental lossless compression techniques: dictionary encoding and run-length encoding. By implementing these methods in Python, we will demonstrate their effectiveness in compressing a list of colours representing the different Lego bricks needed to build a colourful Lego tower.

Dictionary Encoding

Dictionary encoding, also known as substitution encoding, replaces recurring elements with shorter codes or symbols. This technique is effective when the data contains many repetitions. For our LEGO tower, we can use dictionary encoding to replace frequently occurring colours with shorter identifiers as follows:

Run-Length Encoding

Run-length encoding (RLE) is a simple form of data compression where consecutive elements (runs) are stored as a single data value and count. This technique is particularly effective for data with many consecutive repetitions. In our Lego tower, RLE can compress sequences of the same colour into a more compact form:

Combing Dictionary Encoding and Run-Length Encoding

By combining both lossless compression methods it may be possible to reach a higher compression rate, still without losing any data (lossless compression)!

Lossless Compression Algorithms, using Python!

Let’s use our Python skills to implement the two lossless compression techniques described above. To fully understand the code provided below, you will need a good understanding of how lists, dictionaries (a.k.a. hash tables) and tuples work in Python. You may first notice the use of square brackets [] in Python for storing data in a list, the use of curly brackets {} for storing pairs of key:value in a dictionary and the use of standard brackets () to store data in a tuple.

Use the tabs below to investigate how we have implemented our compression algorithms to compress our list of Lego brick colours.

Dictionary EncodingRun-Length EncodingDictionary Encoding + Run-Length Encoding
Our dictionary_compress() function will take one parameter, the data (list of values) to be compressed and return both a compressed list of encoded values as well as a dictionary that would be needed to decompress the data.

# Dictionary Encoding
def dictionary_encoding(data):
   compressedData = []
   dictionary = {}
   reversedDictionary = {}

   for value in data:
      if value not in reversedDictionary:
         key = value[0]     # e.g. "Y" for "Yellow"
         dictionary[key] = value     # "Y":"Yellow"
         reversedDictionary[value] = key  # "Yellow":"Y"
         compressedData.append(key)    # "Y"
      else:
         key = reversedDictionary[value]
         compressedData.append(key)
   return compressedData, dictionary

data = ["Yellow","Yellow","Yellow","Red","Red","Blue","Blue","Blue","Green","Red"]
print(">>> Original Data (Before compression)")
print(data)      
print("")
compressedData, dictionary = dictionary_encoding(data)
print(compressedData)
print(dictionary)
Our run_length_compress() function will take one parameter, the data (list of values) to be compressed and return a list of tuples to indicate the number of consecutive occurrences of each value.

# Run-Length Encoding
def run_length_encoding(data):
   compressedData = []
   currentKey = data[0]
   counter = 1
   for i in range(1,len(data)):
      if data[i]==currentKey:
         counter+=1
      else:
         compressedData.append((currentKey,counter))
         counter=1
         currentKey = data[i]
   compressedData.append((currentKey,counter))  
   return compressedData

data = ["Yellow","Yellow","Yellow","Red","Red","Blue","Blue","Blue","Green","Red"]
print(">>> Original Data (Before compression)")
print(data)      
print("")
compressedData = run_length_encoding(data)
print(compressedData)
We can now create a lossless_compress() function that will reuse both our lossless compression functions: dictionary_compress() and run_length_compress()

# Lossless Compression Algorithms using Python - www.101computing.net/lossless-compression-algorithms-using-python

# Dictionary Encoding
def dictionary_encoding(data):
   compressedData = []
   dictionary = {}
   reversedDictionary = {}

   for value in data:
      if value not in reversedDictionary:
         key = value[0]     # e.g. "Y" for "Yellow"
         dictionary[key] = value     # "Y":"Yellow"
         reversedDictionary[value] = key  # "Yellow":"Y"
         compressedData.append(key)    # "Y"
      else:
         key = reversedDictionary[value]
         compressedData.append(key)
   return compressedData, dictionary

# Run-Length Encoding
def run_length_encoding(data):
   compressedData = []
   currentKey = data[0]
   counter = 1
   for i in range(1,len(data)):
      if data[i]==currentKey:
         counter+=1
      else:
         compressedData.append((currentKey,counter))
         counter=1
         currentKey = data[i]
   compressedData.append((currentKey,counter))  
   return compressedData

# Combining Both Lossless Compression Techniques
def lossless_compression(data):
   print(" >>> Step 1: Dictionary Encoding")
   compressedData, dictionary = dictionary_encoding(data)
   print(" > Compressed Data:")
   print(compressedData)  

   print(" > Dictionary:")
   print(dictionary)
   print("")
   print(" >>> Step 2: Run-Length Encoding")
   fullyCompressedData = run_length_encoding(compressedData)
   print(" > Fully Compressed Data:")
   print(fullyCompressedData)        
   
  
data = ["Yellow","Yellow","Yellow","Red","Red","Blue","Blue","Blue","Green","Red"]
print(">>> Original Data (Before compression)")
print(data)      
print("")
lossless_compression(data)

Try it online…

You can now test these functions using the code provided below…

Python Challenge

Your Python challenge is to write an algorithm to decompress data using a list of compressed data and a given dictionary, your python code will need to reconstruct the original data:

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area

Mnemonic Phrase Validator

Welcome to the Mnemonic Phrase Validator Challenge! This Python challenge is designed to help you practise your coding skills while creating a useful tool for validating mnemonic phrases.

Mnemonic Phrase?

Mnemonic phrases are often used to remember specific sequences or information, such as the order of the planets in the solar system.

The following Mnemonic phrase makes it easier to remember the order of the planets as each word in this sentence starts with the letter corresponding to a planet in the solar system, matching their position from the Sun: from Mercury, closest planet to the Sun to Pluto, furthest planet to the Sun.

My Very Easy Method Just Speeds Up Naming Planets.

Mnemonic Phrase

As you can see this phrase contains all the planets in order: My (Mercury) Very (Venus) Easy (Earth) Method (Mars) Just (Jupiter) Speeds (Saturn) Up (Uranus) Naming (Neptune) Planets (Pluto – dwarf planet)

Python Challenge

For this challenge, you are going to write a Python program based on the Input/Process/Output model:

  1. Input: Accept a phrase from the user.
  2. Process: Define and implement validation rules to check the phrase.
  3. Output: Provide feedback to the user indicating whether the phrase is valid or not.

Validation Checks

To validate a mnemonic phrase we will use the following validation rules:

  • Length: The phrase should be between 10 and 50 characters long.
  • Unique Words: Each word in the phrase should be unique.
  • Alphabetical Characters Only: The phrase should only contain alphabetic characters and spaces.
  • Sequence Matching: Each word must start with the letter corresponding to the sequence we want to learn, in the same order. For example, if remembering the order of the planets, the phrase “My Very Easy Method Just Speeds Up Naming Planets” is valid because each word starts with the first letter of a planet’s name in order.

Let’s see how we can implement these four types of validation checks in Python:

Length CheckUnique WordsAlphabetical Characters OnlySequence Matching
Our first check consists of checking that our mnemonic phrase is long enough but not too long, in other words a valid mnemonic phrase should be between 10 and 100 characters long.

In Python, we can use the len() function to find out the number of characters in a string.

phrase = "My Very Easy Method Just Speeds Up Naming Planets"
if len(phrase)<10 or len(phrase)>100:
      print("Invalid: Phrase length should be between 10 and 100 characters.")
      return False
Our next check consists of checking that the phrase given only include unique words. To implement this check in Python we will first need a list of all the words contained in our phrase. We can create such a list of words using the split() function using the space character to split our phrase into separated words.

phrase = "My Very Easy Method Just Speeds Up Naming Planets"
words = phrase.split()

We can then use the set() function in python which returns a set of unique values from a given list by removing duplicate values. If the resulting set contains as many words as the initial list of words, we can deduct that all the words in the words list must have been unique.

phrase = "My Very Easy Method Just Speeds Up Naming Planets"
# Check for unique words
words = phrase.split()
if len(words) != len(set(words)):
   print("Invalid: Each word should be unique.")
   return False
To check if each word of our phrase only contains alphabetical characters we can use the isalpha() function that returns True if a given string value only contains characters from the alphabet (lowercase or uppercase).

To check the whole sentence, we will first create a list of words as we did in the previous check, using the split() function. We will then iterate through this list of words, to check one word at a time.

phrase = "My Very Easy Method Just Speeds Up Naming Planets"
 # Check for special characters
words = phrase.split()

for i in range(0,len(words)):
   if not words[i].isalpha():
      print("Invalid: Phrase should only contain alphabetic characters and spaces.")
      break #No need to check other words
To check that each word from the phrase starts with the same letter as each word in the given sequence we will loop through our list of words and extract the first characters (at position 0) from the list of words and from the given sequence.

phrase = "My Very Easy Method Just Speeds Up Naming Planets"
sequence = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune","Pluto"]
valid = True
# Check sequence matching
for i in range(0,len(words)):
   if not words[i][0] == sequence[i][0]:
      print("Invalid: Each word must start with the corresponding letter in the sequence.")
      valid=False
      break #No need to check other words
if valid==True:
   print("Valid Sequence Matching!")

Python Code

Your task is to use the techniques mentioned in the four tabs above to complete this Mnemonic Phrase Validator challenge.

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area
Tagged with:

The Vigenère Cipher – Python Challenge

In the world of cryptography, the Vigenère Cipher represents a significant milestone in the evolution of encryption techniques. To fully appreciate its significance, let’s take a step back and explore its roots, starting with the Caesar Cipher.

The Caesar Cipher: A Historical Foundation

The Caesar Cipher, named after Julius Caesar who used it to protect sensitive information, is one of the earliest known encryption methods. It operates by shifting each letter in the plaintext by a fixed number of positions down the alphabet. For example, with a shift of 3, ‘A’ becomes ‘D’, ‘B’ becomes ‘E’, and so on. With this encryption technique the key represents the number used for shifting letters in the alphabet. (e.g. in our example the key is 3).

While simple and effective for its time, the Caesar Cipher is easy to break. Effectively, with the Caesar Cipher there are only 26 possible keys, so it’s easy to try them all to decode an encrypted message. The Caesar Cipher is also vulnerable to frequency analysis, where the frequency of letters in the ciphertext is analysed to deduce the original message. This limitation paved the way for more complex encryption methods, including the Vigenère Cipher.

The Vigenère Cipher: Enhancing Security

The Vigenère Cipher, invented by Blaise de Vigenère in the 16th century, builds upon the principles of the Caesar Cipher but introduces a significant enhancement: it uses a keyword to determine the shift for each letter in the plaintext. This means that instead of a single shift value, the Vigenère Cipher employs a different shift for each letter of the message to encrypt, making it much harder to crack using a frequency analysis. It also means that any keyword (or sequence of letters) can be used as the key which exponentially increases the number of possible unique keys available and making it virtually impossible for a human being to try all the possible keys one at a time.

How the Vigenère Cipher Works

Step 1: Choose the key: Decide on a keyword that will be used to encrypt the message. For example, let’s use the keyword “CRYPTO”

Step 2: Align the key with the plaintext: Align the keyword along the length of the plaintext. As the plaintext message will most likely be longer than the key, you may have to repeat the key. For instance ff the plaintext is “VIGENERECIPHER” and the KEY is “CRYPTO” the alignment would look like this:

Plaintext: V I G E N E R E C I P H E R
Keyword:   C R Y P T O C R Y P T O C R

Step 3: Apply Caesar Shift Encryption: Shift each letter in the plaintext by the position in the alphabet of the corresponding letter of the key. For instance, ‘V’ is shifted by ‘2’ as ‘C’ is at position 2 in the alphabet (we start with position 0 for ‘A’) so ‘C’ becomes ‘X’, whereas ‘I’ is shifted by 17 as ‘R’ is at position 17 in the alphabet.

Python Challenge: Implementing the Vigenère Cipher

Now that you have a basic understanding of both the Caesar Cipher and the Vigenère Cipher, it’s time to put your programming skills to the test! Below is a Python challenge to implement both ciphers.

Tips:
Convert the plaintext and keyword to uppercase to handle case sensitivity.
Use the ASCII values of the letters to perform the shifts.
When shifting a letter, if the resulting letter is after Z, it should go back to the start of the alphabet. (e.g. ‘X’ shifted by 3 becomes ‘A’)
For the Vigenère Cipher, ensure the key repeats to match the length of the plaintext.

Getting Started: Caesar Cipher

The following code will help you identify the main steps of a Caesar Cipher algorithm:

plaintext="CAESAR"
key = 3
cipher = ""
# Parse through the plaintext, one character at a time
for i in range(0, len(plaintext)):
   #Retrieve the ASCII value for the current character
   ascii = ord(plaintext[i])
   #Only encrypt letters from the alphabet, from A=65 to Z=90
   if ascii>=65 and ascii<=90: 
      # Encrypt the letter by shifting the ASCII value by the key
      ascii = ascii + key
      # If the new encrypted letter is after Z, it goes back to A
      if ascii > 90:
         ascii = ascii - 26
   cipher = cipher + chr(ascii)

Extension Task:

Extend your implementation to include two decryption functions that take the encrypted text and the key as inputs and return the original plaintext.

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area